<template>
  <!-- 新建账单 -->
  <div class="flex-d-c" v-loading="loading">
      <div class="charge-c-l" v-if="isPutItAway">
        <div class="charge-tree-title">收费项目列表</div>
        <div class="charge-tree-select">
          <!-- <el-select class="select-2" v-model="notyet"  placeholder="暂无选择">
            <el-option
              v-for="item in NotyetOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select> -->
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="notyet"
            clearable
            >
          </el-input>
        </div>
        <div class="charge-tree">
          <el-tree
            ref="treeRef"
            :props="defaultProps"
            :data="treeData"
            :filter-node-method="filterNode"
            @node-click="handleNode"

            >
          </el-tree>
        </div>
      </div>
      <div class="charge-c-r"  :class="{'w100' : !isPutItAway}">
        <!-- <header class="charge-r-head">
          <div class="head-left-btns" >
            <el-button v-if="isPutItAway" class="btn-7" icon="el-icon-arrow-left" @click="handPut()"></el-button>
            <el-button v-else class="btn-7" icon="el-icon-arrow-right" @click="handOpen"></el-button>
            <el-select class="select-2" v-model="notyet"  placeholder="暂无选择">
              <el-option
                v-for="item in NotyetOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="head-right-btns">
            <el-button class="btn-2" >保存并划价预览</el-button>
            <el-select class="select-3" v-model="notyet"  placeholder="暂无选择">
              <el-option
                v-for="item in NotyetOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </header> -->
        <div class="charge-r-content">

            <el-table
              :data="addProjectList"
              style="width: 100%"
              :header-cell-style="{background:'#fff', color:'#000'}"
              >
              <el-table-column
                v-for="(item) in MockColumns"
                :key="item.name"
                :prop="item.name"
                :label="item.lable"
                :width="item.name === 'toothBit' ? '120' : ''"
                align="center"
                
                >
                <template #default="scope">
                  <div v-if="item.name === 'toothBit'" >
                    <div style="">
                      <ztooth 
                        :lTToolist="scope.row[item.name].leftTop" 
                        :rTToolist="scope.row[item.name].rightTop" 
                        :lBToolist="scope.row[item.name].leftBottom" 
                        :rBToolist="scope.row[item.name].rightBottom"
                        @getLeftData="(() => getLeftData(scope.$index))()"
                        @getRightData="(() => getRightData(scope.$index))()"
                        @getLeftBottomData="(() => getLeftBottomData(scope.$index))()"
                        @getRightBottomData="(() =>getRightBottomData(scope.$index))()"
                        ></ztooth>
                    </div>
                  </div>
                  <template v-else-if="item.name === 'realPriceShow'">
                    <el-input v-model="scope.row[item.name]" @change="handleChange"  class="mini-btn"></el-input>
                  </template>
                  <template v-else-if="item.name === 'number'">
                    <el-input v-model="scope.row[item.name]" @change="handleChange" class="mini-btn"></el-input>
                  </template>
                  <template v-else-if="item.name === 'money'">
                    <el-input v-model="scope.row[item.name]"  class="mini-btn"></el-input>
                  </template>
                  <!-- <template v-else-if="item.name === 'realPriceShow'">
                    <el-input v-model="scope.row[item.name]"  class="mini-btn"></el-input>
                  </template> -->
                  <template v-else-if="item.name === 'doctorId'">
                    <!-- <el-input v-model="scope.row[item.name]"  class="mini-btn"></el-input> -->
                    <el-select class="select-4" 
                      v-model="scope.row[item.name]" 
                      filterable
                      remote
                      :remote-method="remoteMethod"
                      placeholder="请选择">
                      <el-option
                        v-for="item in optionsDoctors"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                  <template v-else-if="item.name === 'nurseId'">
                    <el-select class="select-4" 
                      v-model="scope.row[item.name]" 
                      filterable
                      remote
                      :remote-method="remoteMethodNurse"
                      placeholder="请选择"
                      >
                      <el-option
                        v-for="item in optionsNurse"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                  <template v-else-if="item.name === 'consultantId'">
                    <el-select class="select-4" 
                      v-model="scope.row[item.name]" 
                      filterable
                      placeholder="请选择"
                      >
                      <el-option
                        v-for="item in secondaryUserOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                  <div v-else>{{scope.row[item.name]}}</div>
                </template>
              </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template #default="scope">
                    <el-button
                      @click="del(scope.row, scope.$index)"
                      type="text"
                      size="small"
                      class="btn-text"
                    ><el-icon><delete /></el-icon></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="charge-r-total">
              <div class="total-order">
                <div class="label">整单折扣率</div>
                <el-input  v-model="wholeOrderDiscount" :disabled="isDisable" class="mini-btn"></el-input>%
              </div>
              <span>总计金额: {{ orderDetailSumMoneyShow || '00.00'}}</span>
              <div class="copeWith">
                <div class="label">应付金额: </div>
                <el-input  v-model="originalPriceShow" :disabled="isDisable" @change="handleOriginalPriceShowChange" class="mini-btn"></el-input>
              </div>
            </div>
            <!-- 后面动态添加 -->
            <div class="main-content">
              <el-row align="middle">
                <el-col :span="3">创建时间</el-col>
                <el-col :span="8">
                  <el-date-picker
                    v-model="createTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择时间"
                  />
                </el-col>
              </el-row>
              
              <component :is="showWidget(item.type)"  v-for="item in orderDetailInfo" :key="item.name" :struc="item"  />
              <!-- <div class="leftToRight-layout">
                  <div class="label">
                    <span>备注</span>
                  </div>
                  <div class="operations">
                    <el-input
                      type="textarea"
                      :rows="4"
                      placeholder="请输入内容"
                      v-model="planContent"
                      >
                    </el-input>
                  </div>
                </div> -->
            </div>
            <!-- 展示账单 -->
            <div class="arrears" v-if="false">
              <header class="arrears-head">
                <span class="total">历史欠费: </span>
                <span>{{totalArrears || 0}}</span>
              </header>
              <div class="arrears-content">
                <ztable :tableData='arrearsData' :strucs='arrearsColumns' :isShow="true"
                        type='selection'
                        @handleSelectionChange="handleSelectionChange"
                ></ztable>
              </div>
              <!-- 预付款 -->
              <div class="advance">
                <div class="advance-head">
                  <div class="head-title">
                    <span class="total">预付款: </span>
                    <span>0.0</span>
                    <span>积分: 0</span>
                    <span>(抵现: 0.0)</span>
                  </div>
                  <div class="head-btn">
                    <el-icon><edit /></el-icon>
                    <el-icon><sort /></el-icon>
                  </div>
                </div>
                <div class="advance-content">
                    <div class="group" v-for="(item, index) in payment" :key="index">
                      <div class="group-left">
                        <div class="label">支付方式: </div>
                        <el-select class="select-3 machin-select" v-model="item.payType"  placeholder="请选择">
                          <el-option
                            v-for="(item, index) in paymentOptions"
                            :key="item.id + '' + index"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                        <div class="label">实付金额: </div>
                        <el-input class="input-5" type="text" v-model="item.moneyShow">
                            <template #prepend>￥</template>
                          </el-input>
                      </div>
                      <div class="group-right">
                        <el-icon v-if="item.isAdd" @click="addPayment"><plus /></el-icon>
                        <el-icon v-else @click="delPayment(index)"><minus /></el-icon>
                        
                      </div>
                    </div>
                </div>
              </div>
              <!-- 欠费 -->
              <div class="owe">
                <header class="owe-head">
                  <div class="head-l">
                    <span>欠费: </span>
                    <span>00.00</span>
                  </div>
                  <div class="head-r">
                    <span>实付总额: </span>
                    <span>{{realPrice || 0}}</span>
                  </div>
                  <span></span>
                </header>
                <div class="owe-conntent flex-wrap">
                    <!-- <span>客户</span>
                    <el-select class="select-3 machin-select" v-model="customerId"  placeholder="请选择">
                        <el-option
                          v-for="item in customerOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                    </el-select> -->

                    <!-- <div class="leftToRight-layout" style="width: 20%;">
                      <div class="label f-14" style="width: auto;">
                        <span>医生</span>
                      </div>
                      <div class="operations">
                        <el-select class="select-3 machin-select" v-model="masterUserId"  placeholder="请选择">
                          <el-option
                            v-for="item in optionsDoctors"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                      </el-select>
                      </div>
                    </div>
                    <div class="leftToRight-layout"  style="width: 20%;">
                      <div class="label f-14" style="width: auto;">
                        <span>咨询师</span>
                      </div>
                      <div class="operations">
                        <el-select class="select-3 machin-select" v-model="secondaryUserId"  placeholder="请选择">
                          <el-option
                            v-for="item in secondaryUserOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                      </el-select>
                      </div>
                    </div> -->
                </div>
              </div>
            </div>

        </div>
        <div class="charge-r-f">
          <div class="btns">
            <!-- <el-button class="btn-2" @click="handlePrint">打印</el-button>
            <el-button class="btn-2" @click="handleCoupon">发优惠券</el-button>
            <el-button class="btn-2" @click="handleClose">关闭</el-button>
            <el-button class="btn-1" @click="handleCharge">收费</el-button> -->

            

          </div>
        </div>
      </div>
    </div>

    <zdialog title="发放优惠券" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <div class="leftToRight-layout">
            <div class="label" style="width: 100px">
              <span>优惠券模板</span>
            </div>
            <div class="operations">
              <el-select v-model="modelId"  placeholder="请选择">
                <el-option
                  v-for="item in modelOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>数量</span>
            </div>
            <div class="operations">
              <el-input-number v-model="count" :min="1" :max="10" ></el-input-number>
            </div>
          </div>
        </div>
        
			</template>
    </zdialog>
</template>

<script lang="ts">
import { Plus, Sort, Minus, Edit, Delete } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, toRefs, computed, inject, PropType, watch, onMounted } from 'vue'
import ztable from "../../../../components/Table/index.vue"
import ztooth from "../../../../components/tooch/imgTooth.vue"
import zdialog from '@components/dialog/dialog.vue'

import { getNowDate } from "../../../../utils/nowDate"

import useShowWidget from "../../../../components/widget/usechoose"
import {TemOption, Option} from "../../../../types"
import { getToothData } from "../../../../usefn/getToothData"
import { filterTree } from "../../../../usefn/setTreeData"


import { getDoctorListAllAPi, getNurseListAllAPi, getConsultListAllAPi } from "../../../../api/common"

import useRequet, { RespData } from "../../../../hook/network"
import { ElMessage } from 'element-plus'
import useUser from '../../../../hook/user'
import { useRouter, useRoute } from 'vue-router'


type MockTree = {
  id: number,
  name: string,
  leaf?: boolean,
  unit?: string,
  realPrice?: number | string
  // children: MockTree[]
}

type AddProjectList = {
  toothBit: any,
  itemName: string,
  projectCode?: string,
  unit: string,
  priceShow: string,
  number: string,
  money: string,
  realPriceShow: string,
  doctorId: string,
  nurseId: string,
  remark?: string,
  itemId: number
}

type PayMoneys = {
  payType: string,
  moneyShow: string
}

type Doctors = {
  id: number,
  name: string,
  status?: string
}
type MockType = {
  id: string,
  isActive: boolean,
  // index: number,
}
export default defineComponent({
  props: {
    id: {
      type: String
    },

    historyData: {
      type: Array as PropType<AddProjectList[]>,
      default: []
    },

    orderId: {
      type: Number,
      default: 0
    }
  },
  components: {
    ztable,
    ztooth,
    zdialog,

    Plus, Sort, Minus, Edit, Delete
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    let id = route.params.id
    watch(() => route.params.id, (newID, prevID) => {
      id = newID
      if(newID) {
        getLastOrderAdd(newID as string)
        getCustomerDebtOrder(newID as string)
      }
      
    })
    const showWidget = useShowWidget;
    const request = useRequet({ path: "" });
    const isPutItAway = ref(true)
    const list = reactive({
      itemizeList:[] as MockTree[], // 分类
      itemList: [], //列表
      defaultProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      loading: false,
      treeData:[],
      // 收欠费支付方式
      payment:[
        {
          isAdd: true, // 是否显示添加
          payType: '', // 支付方式
          moneyShow: '' // 实付金额
        }
      ],

      // 新建账单-》欠费列表
      arrearsData: [],
      arrearsColumns: [
        {
           id: 529,
            name: "createTime",
            viewName: "创建时间",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "masterUserName",
            viewName: "医生",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "originalPriceShow",
            viewName: "应收",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "amountMoneyShow",
            viewName: "实收",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "remark",
            viewName: "备注",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        }
      ] as any[],
      arrearsList: [] as number[],

      // 暂无
      NotyetOptions:[
        {
          value:'',
          label:''
        }
      ],
      notyet: '',
      
    })
    const treeRef = ref<any>(null)

    const masterUserId = ref('')
    const secondaryUserId = ref('')
    const recordId = ref('')

     // 牙齿数据
    const lTToolist = ref(getToothData())
    const rTToolist = ref(getToothData())
    const lBToolist = ref(getToothData())
    const rBToolist = ref(getToothData())

    const getLeftData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftTop = data
      }
    }
    const getRightData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightTop = data
      }
    }

    const getLeftBottomData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftBottom = data
      }
    }

    const getRightBottomData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightBottom = data
      }
    }
    // 获取账户id
    const user = useUser();
    // 牙树形
    const handleNode = (data: any) => {
      let leftTop = JSON.parse(JSON.stringify(lTToolist.value))
      let rightTop = JSON.parse(JSON.stringify(rTToolist.value))
      let leftBottom = JSON.parse(JSON.stringify(lBToolist.value))
      let rightBottom = JSON.parse(JSON.stringify(rBToolist.value))
      
      if(data?.leaf) {
        addProjectList.value.push({
          toothBit: {
            leftTop,
            rightTop,
            leftBottom,
            rightBottom
          },
          itemName: setItemName(data.name),
          // projectCode: '000000',
          unit: data.unit,
          priceShow: data.realPrice,
          number: '1',
          realPriceShow: data.realPrice || '0',
          doctorId: window.localStorage.getItem('doctorId') ? window.localStorage.getItem('doctorId') : null,
          nurseId: '',
          consultantId: '',
          remark: '',
          itemId: data.id,
        })

        wholeOrderDiscount.value = 100;
        originalPriceShow.value = 0;

        //选中就开始核算
        handleAccountingOrder()

      }
      

      list.notyet = ''
    }

    const setItemName = (name: string) => {
      return name.split(',')[0]
    }

    // 整单折扣
    const wholeOrderDiscount = ref<number | string>(100);
    // 处理折扣百分比
    watch(() => wholeOrderDiscount.value, (newV) => {
      if(newV) {
          if(!isNaN(Number(newV))) {
            if(newV > 100) {
              wholeOrderDiscount.value = 100
            } else if (newV < 0) {
              wholeOrderDiscount.value = 0
            }

            // 应付金额
            originalPriceShow.value = (Number(orderDetailSumMoneyShow.value) * Number(wholeOrderDiscount.value)) / 100

          } else {
            wholeOrderDiscount.value = 100
          }
      } else {
        wholeOrderDiscount.value = 0
      }

    })
    // 是否可修改
    const isDisable = ref(true)
    // 新建账单 牙项目表格
    const theadList = ref([
      {
        head: '牙位',
      },
      {
        head: '项目名称',
      },
      {
        head: '项目编码',
      },
      {
        head: '单位',
      },
      {
        head: '单价',
      },
      {
        head: '数量',
      },
      {
        head: '金额',
      },
      {
        head: '折扣%',
      },
      {
        head: '医生',
      },
      {
        head: '护士',
      },
      {
        head: '操作',
      }
    ])

    // 新增表格结构
    const MockColumns = [
      {
        name: 'toothBit',
        lable: '牙位'
      },
      {
        name: 'itemName',
        lable: '项目名称'
      },
      // {
      //   name: 'projectCode',
      //   lable: '项目编码'
      // },
      {
        name: 'unit',
        lable: '单位'
      },
      {
        name: 'priceShow',
        lable: '单价'
      },
      {
        name: 'realPriceShow',
        lable: '金额'
      },
      {
        name: 'number',
        lable: '数量'
      },
      // {
      //   name: 'money',
      //   lable: '金额'
      // },
      
      {
        name: 'doctorId',
        lable: '医生'
      },
      {
        name: 'nurseId',
        lable: '护士'
      },
      {
        name: 'consultantId',
        lable: '咨询师'
      },
    ]

    
    // 新建账单 新增项目
    const addProjectList = ref([] as any[])

    watch(() => (props.historyData), (newData: AddProjectList[]) => {
      addProjectList.value = newData
      handleAccountingOrder()
    })

    watch(() => addProjectList.value, (newList) => {
      // 有值
      if(newList.length > 0) {
        isDisable.value = false
      } else {
        isDisable.value = true
      }
    },{
      immediate: true
    })

    // 获取所有物品列表树
    const getTypeAndItemTree = () => {
      request.sendRequest({
        address: `pay/order/getTypeAndItemTree`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data, '获取所有物品列表树')
          filterTree(resp.data)
          list.treeData = resp.data
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    getTypeAndItemTree()

    watch(() => list.notyet, (newV) => {
      treeRef.value.filter(newV)
    })
    // 筛选树
    const filterNode = (val: string, data: any) => {
      if (!val) return true;
      return data.name.indexOf(val) !== -1;
    }

    // 动态账单附加数据
    const orderDetailInfo = ref<any[]>([
      {
         id: 529,
            name: "remark",
            viewName: "备注",
            type: 103,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
          columnWidth:'',
      }
    ])
    const createTime = ref(getNowDate())
    const addPayment = () => {
      list.payment.push({
        isAdd: false,
        payType: '',
        moneyShow: '',
      })
    }

    const delPayment = (index: number) => {
      list.payment.splice(index, 1)
    }

    // 历史欠费
    // 获取患者欠费订单
    const getCustomerDebtOrder = (id: string | number) => {
      list.loading = true
      list.arrearsData = []
      request.sendRequest({
        address: `pay/order/getCustomerDebtOrder/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          list.arrearsData = resp.data

          list.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    
    const handleSelectionChange = (data: any) => {
      let arr: number[] = []
      data.forEach((item: any) => {
        arr.push(item.id)
      })
      
      list.arrearsList = arr
    }
    
    // 订单原价 
    const orderDetailSumMoneyShow = ref(0)
    // 实际应付款（折后价）
    const originalPriceShow = ref(0)
    const handleOriginalPriceShowChange = (e: number) => {
      console.log(e)
      if(e) {
        if(!isNaN(Number(e))) {
          if(e > orderDetailSumMoneyShow.value) {
            originalPriceShow.value = orderDetailSumMoneyShow.value
          } else if (e < 0) {
            originalPriceShow.value = 0
          }

          // 处理折扣显示
          wholeOrderDiscount.value = ((Number(originalPriceShow.value) / Number(orderDetailSumMoneyShow.value)) * 100).toFixed(2)
        } else {
          originalPriceShow.value = orderDetailSumMoneyShow.value
        }
      } else {
        originalPriceShow.value = orderDetailSumMoneyShow.value
      }

      handleAccountingOrder()

    }
  
    // 订单核算
    const handleAccountingOrder = () => {
      let params = {
        customerId: Number(id),
        masterUserId: '',
        secondaryUserId: '',
        useCouponsIds: [],
        details: addProjectList.value,
        createTime: createTime.value,
        originalPriceShow: originalPriceShow.value
      }
      request.sendRequest({
        address: 'pay/order/accountingOrder',
        params,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          originalPriceShow.value = resp.data.originalPriceShow || 0
          orderDetailSumMoneyShow.value = resp.data.orderDetailSumMoneyShow || 0
          addProjectList.value = resp.data.details || []

        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const handleChange = () => {
      originalPriceShow.value = 0
      handleAccountingOrder()
    }

    // 支付方式
    const paymentOptions = ref([] as Option[])
    const payType = ref('')
    const moneyShow = ref('')
    const getPayMent = () => {
      request.sendRequest({
        address: 'pay/order/getCustomerType',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          paymentOptions.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    

    // 历史欠费
    const totalArrears = computed(() => {
      let result = 0
      list.arrearsData.forEach((item: any) => {
        result += item.originalPriceShow
      })
      return result
    })
    

    // 实际总额
    const realPrice = computed(() => {
      let result = 0
      list.payment.forEach(item => {
        return result += Number(item.moneyShow)
      })
      return result
    })

    onMounted(() => {
      getDoctorListAll()
      getNurseListAll()
      getConsultListAll()
    })

    // 医生下拉数据
    const sourceDoctorAll = ref([] as Doctors[])
    const optionsDoctors = ref([] as Doctors[])
    const sourceNurseAll = ref([] as Doctors[])
    const optionsNurse = ref([] as Doctors[])
    const sourceSecondaryAll = ref([] as Doctors[])
    const secondaryUserOptions = ref([] as Doctors[])
    let doctor:any = window.localStorage.getItem('doctor')

    // 处理数据
    const setDataSource = (source: Doctors[], length: number, cur: Doctors[]) => {
      // 源数据少于 10条
      if(source.length < length) {
        cur = source
      } else {
        // 大于的话 就取前10条
        for(let i = 0; i < length; i++) {
          cur.push({
            id: source[i].id,
            name: source[i].name
          })
        }
      }
      

      return cur
    }
    // 添加默认医生下拉
    const addDefaultDoctor = () => {
      let dortorObj = JSON.parse(doctor)
      let arr = optionsDoctors.value.filter(i => i.id === dortorObj.id)
      if(arr.length === 0) {
        optionsDoctors.value.push(dortorObj)
      }
    }

    // 获取医生
    const getDoctorListAll = async(name?:string) => {
      let res:any = await getDoctorListAllAPi({});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      sourceDoctorAll.value = res.data;
      console.log(sourceDoctorAll.value)

      let arrList = setDataSource(sourceDoctorAll.value, 10, [])
      console.log(arrList)
      optionsDoctors.value = arrList

      addDefaultDoctor()
      
    }
     // 获取护士
    const getNurseListAll = async(name?:string) => {
      let res:any = await getNurseListAllAPi({name: name || ''});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      sourceNurseAll.value = res.data;

      let arrList = setDataSource(sourceNurseAll.value, 10, [])
      optionsNurse.value = arrList

    }
    
    // 获取咨询师
    const getConsultListAll = async(name?:string) => {
      let res:any = await getConsultListAllAPi({name: name || ''});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      sourceSecondaryAll.value = res.data;

      let arrList = setDataSource(sourceSecondaryAll.value, 10, [])
      secondaryUserOptions.value = arrList

    }
    
    // 过滤函数
    const remoteMethod = (query: string) => {
      console.log(query)
      
      let res = sourceDoctorAll.value.filter(i => i.name.includes(query))
      if(res.length) {
        optionsDoctors.value = res
      } else {
        let arrList = setDataSource(sourceDoctorAll.value, 10, [])
        optionsDoctors.value = arrList
      }
      console.log(res)

      addDefaultDoctor()
      
    }

    // 护士过滤
    const remoteMethodNurse = (query: string) => {
      console.log(query)
      
      let res = sourceNurseAll.value.filter(i => i.name.includes(query))
      if(res.length) {
        optionsNurse.value = res
      } else {
        let arrList = setDataSource(sourceNurseAll.value, 10, [])
        optionsNurse.value = arrList
      }
      
    }


    const del = (data: any, index: number) => {
      addProjectList.value.splice(index, 1)
      // 重新核算
      wholeOrderDiscount.value = 100;
      originalPriceShow.value = 0;
      handleAccountingOrder()
    }

    const handOpen = () => {
      isPutItAway.value = true
    }

    // 项目列表展开收起
    const handPut = () => {
      isPutItAway.value = false
    }

    let orderID = props.orderId
    watch(() => props.orderId, (newOrderID) => {
      console.log('newbill-orderID', newOrderID, orderID)
      orderID = newOrderID
    })
    // 保存账单(未下单)
    const saveOrderData = () => {
      if(addProjectList.value.length <= 0) {
        ElMessage.warning('您还未选择项目')
        return false
      } else {
        type OrderParam = {
          id?: number,
          customerId: number,
          details: any[],
          remark?: string
          createTime: string
          originalPriceShow: number
        }
        let params:OrderParam = {
          id: orderID,
          customerId: Number(id),
          details: addProjectList.value,
          createTime: createTime.value,
          originalPriceShow: originalPriceShow.value
        }
        let res = orderDetailInfo.value.find(i => {
          return i.name === 'remark'
        })
        if(res) {
          params.remark = res.value
        }

        function tips(item: any) {
          return item.doctorId
        }

        let isDoctor = addProjectList.value.every(tips)
        if(!isDoctor) {
          ElMessage.warning('请选择医生')
          return false
        }
        console.debug(params)
        request.sendRequest({
          address: '/pay/order/onlySaveOrder',
          params,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('保存' + resp.msg)
            ElMessage.success('保存' + resp.msg)
            addProjectList.value = []
            orderDetailSumMoneyShow.value = 0
            originalPriceShow.value = 0

            isDisable.value = true
            wholeOrderDiscount.value = 100

            orderDetailInfo.value.forEach(i => i.value = '')

          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "POST",
        })
      }
    }
    // 获取最后一张新建订单
    const getLastOrderAdd = (id: number | string) => {
      addProjectList.value = []
      orderDetailSumMoneyShow.value = 0
      originalPriceShow.value = 0
      orderDetailInfo.value.forEach(i => i.value = '')
      request.sendRequest({
          address: `pay/order/getCustomerLastAddOrder/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取最新订单' + resp.msg)
            
            if(resp.data) {
              let lastOrder = resp.data || {}
              let lastOrderDetails = lastOrder.details
              lastOrderDetails.forEach((i: { toothBit: string }) => {
                i.toothBit = JSON.parse(i.toothBit)
              })

              // 加id
              orderID = lastOrder.id

              addProjectList.value = lastOrderDetails
              orderDetailSumMoneyShow.value = lastOrder.orderDetailSumMoneyShow || 0
              originalPriceShow.value = lastOrder.originalPriceShow || 0
              orderDetailInfo.value.forEach(i => {
                if(i.name === 'remark') {
                  i.value = lastOrder.remark
                }
              })
            }
            
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "GET",
        })
    }
    
    // 新建账单保存去收费
    const saveToCharge = () => {
      if(addProjectList.value.length > 0) {
        function tips(item: any) {
          return item.doctorId
        }
        let isDoctor = addProjectList.value.every(tips)
        if(!isDoctor) {
          ElMessage.warning('请选择医生')
          return false
        } else {
          saveOrderData()
          router.push({path:`/allPatientDetails/${id}/chargeModel`, query: {type: 4, to: 'CHARGE'}})
          // 去待收费
          // router.push('/waitingCharge')
        }
      } else {
        ElMessage.warning('您还未选择项目')
        return false
      }

    }
    // 重置收费
    const orderReset = () => {
      list.payment = [
        {
          isAdd: true, // 是否显示添加
          payType: '', // 支付方式
          moneyShow: '' // 实付金额
        }
      ]
      addProjectList.value = []
      list.arrearsList = []
    }
    // 新建账单收费
    const handleCharge = () => {
      // 支付方式
      let payMoneys = [] as PayMoneys[]
      
      list.payment.forEach(item => {
        payMoneys.push(item)
      })
      // 优惠券
      let couponIds = [] as any

      // 订单内容
      let order = {
        customerId: id,
        details: addProjectList.value || [],
        useCouponsIds: couponIds,
        
      }
      if(addProjectList.value.length === 0) {
        return ElMessage.warning('还未选择订单')
      }
      if(!orderDetailSumMoneyShow.value) {
        return ElMessage.warning('订单还未核算')
      }
      request.sendRequest({
        address: 'pay/order/payOrder',
        params: {
          arrearsOrderIds: list.arrearsList || [],
          payMoneys,
          order,
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          ElMessage.success('收费' + resp.msg)
          orderReset()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const dialogVisible = ref(false)
    const modelOptions = ref([] as TemOption[])
    const modelId = ref('')
    const count = ref('')
    const closeDialog = () => {
      dialogVisible.value = false
    }
    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
          if(id && modelId.value && count.value) {
            request.sendRequest({
              address: 'pay/coupons/getIssueCouponsModel',
              params: {
                customerId: id,
                modelId: modelId.value,
                count: count.value
              },
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
                ElMessage.success('发送'+ resp.msg)
                closeDialog()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                
              },
              method: "GET",
            })
          } else {
            ElMessage.warning('请选择必要参数')
          }
          
				}
      }
    ]

    const getmodelOptions = () => {
      request.sendRequest({
        address: 'pay/coupons/getIssueCouponsModel',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          modelOptions.value = resp.data
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    const handlePrint = () => {
      ElMessage('功能还在完善,敬请期待......');
    }

    const handleCoupon = () => {
      getmodelOptions()
      dialogVisible.value = true
      // ElMessage('功能还在完善,敬请期待......');
    }

    const handleClose = () => {
      ElMessage('功能还在完善,敬请期待......');
    }
    return {
      showWidget,
      isPutItAway,
      handOpen,
      handPut,
      ...toRefs(list),

      // 账单订单附件信息
      orderDetailInfo,
      createTime,

      wholeOrderDiscount,
      isDisable,

      // 订单核算
      orderDetailSumMoneyShow,
      originalPriceShow,
      handleChange,
      handleAccountingOrder,
      // 应付金额修改
      handleOriginalPriceShowChange,
      // 历史欠费
      handleSelectionChange,
      
      getLastOrderAdd,
      getPayMent,
      getCustomerDebtOrder,

      remoteMethod,
      remoteMethodNurse,


      saveOrderData, // 保存未下单

      handleNode,
      // saveOrder, // 新建保存
      saveToCharge,
      handleCharge,
      handlePrint,
      handleCoupon,
      handleClose,

      lTToolist,
      rTToolist,
      lBToolist,
      rBToolist,
      getLeftData,
      getRightData,
      getLeftBottomData,
      getRightBottomData,

      del,

      theadList,
      addProjectList,
      paymentOptions,
      payType,
      moneyShow,
      totalArrears,
      realPrice,
      MockColumns,
      masterUserId,
      secondaryUserId,
      recordId,

      addPayment,
      delPayment,

      optionsDoctors,
      optionsNurse,
      secondaryUserOptions,

      dialogVisible,
      closeDialog,
      dialogBtnData,
      modelOptions,
      modelId,
      count,

      treeRef,
      filterNode,

      request,
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@style/extend';
.flex-d-c {
  display: flex;
  padding: 20px;
  height: 100%;
  min-height: 600px;
  box-sizing: border-box;
}

.charge-c-l {
  width: 28%;
  // width: 28%;
  // width: 220px;
  // border: 1px solid $mainColor;
  overflow-y: auto;
  transition: .5s linear;
  box-shadow: 0 2px 10px #e9e9e9;
  border-radius: 4px;
  .charge-tree-title {
    padding-left: 20px;
    padding-top: 10px;
    padding-bottom: 10px;
    @extend .standard-5;
    font-size: $fontSize-2;
    
  }
  .charge-tree {
    .collapse {
      width: 100%;
      .collapse-child {
        // height: 30px;
        line-height: 30px;
        cursor: pointer;
        .open {
          padding-left: 10px;
        }
        .mize {
          padding-left: 25px;
        }
      }
      .collapse-child:hover {
        background: $mainColor;
        color: white;
      }
    }
  }
  .charge-tree-select {
    padding-left: 5px;
    padding-bottom: 20px;
    padding-right: 5px;
  }

}
.charge-c-r {
  width: 72%;
  // width: calc(100% - 220px);
  margin-left: 10px;
  box-sizing: border-box;
  border: 2px solid $mainColor;
  overflow-y: auto;
  .charge-r-head {
    height: 40px;
    line-height: 40px;
    display: flex;
    box-sizing: border-box;
    padding: 0 20px 0 20px;
    border-bottom: 1px solid $mainColor;
    .head-left-btns {
      & > .btn-7:first-child {
        margin-right: 10px;
      }
    }
    .head-right-btns {
      flex: 1;
      text-align: right;
      & > .btn-2:first-child {
        margin-right: 10px;
      }
    }
  }
  .charge-r-content {
    // padding: 0;
    // padding-bottom: 10px;
    .charge-r-total {
      height: 40px;
      line-height: 40px;
      display: flex;
      font-size: $fontSize-1;
      .total-order {
        display: flex;
        align-items: center;
        padding: 10px;
        margin-left: 10px;
        flex: 1;
        .label {
          margin-right: 20px;
        }
      }

      .copeWith {
        display: flex;
        align-items: center;
        padding: 10px;
        margin-left: 10px;
        margin-right: 10px;
        .label {
          margin-right: 20px;
        }
      }
      & > span:nth-child(1) {
        flex: 1;
        text-align: right;
        display: inline-block;
        padding-right: 15px;
      }
      & > span:nth-child(2) {
        padding-right: 15px;
        font-size: $fontSize-1;
        font-weight: 600;
      }
    }
  }
  .charge-r-f {
    display: flex;
    .btns {
      height: 40px;
      line-height: 40px;
      flex: 1;
      text-align: right;
      padding-right: 15px;
    }
  }
}


.arrears {
  // border: 2px solid $mainColor;
  border-radius: 4px;
  .arrears-head {
    height: 40px;
    line-height: 40px;
    background: $a2-Color;
    padding-left: 10px;
    @extend .standard-4;
    border-bottom: 2px solid $mainColor;
  }
  .arrears-head > span:last-child {
    color: $a4-Color;
    padding-left: 10px;
  }
  .arrears-content {
    padding: 10px 20px;
  }

  .advance {
    border-top: 2px solid $mainColor;
    .advance-head {
      height: 40px;
      line-height: 40px;
      background: $a2-Color;
      border-bottom: 2px solid $mainColor;
      display: flex;
      @extend .standard-4;
      .head-title {

      }
      .head-title > span{
        padding-left: 10px;
      }
      .head-title > span:nth-child(2) {
        padding-left: 0;
      }
      .head-btn {
        flex: 1;
        text-align: right;
        padding-right: 10px;
        & > i {
          @extend .standard-10;
          padding-left: 10px;
          cursor: pointer;
        }
      }
    }
    .advance-content {
      padding: 20px;
      .group {
        font-size: $fontSize-1;
        display: flex;
        align-items: center;
        background: $a2-Color;
        height: 40px;
        .group-left {
          display: flex;
          align-items: center;
          font-size: $fontSize;
          .label {
            padding: 0 10px;
          }
        }
        .group-right {
          flex: 1;
          text-align: right;
          padding-right: 10px;
          @extend .standard-10;
          & > i {
            cursor: pointer;
          }
        }
      }
    }
  }

  .owe {
    border-top: 2px solid $mainColor;
    .owe-head {
      height: 40px;
      line-height: 40px;
      display: flex;
      padding-left: 10px;
      @extend .standard-4;
      justify-content: space-evenly;
      .head-l {
        & > span:last-child {
          color: $a4-Color;
          padding-left: 10px;
        }
      }
      .head-r {
        flex: 1;
        text-align: right;
        padding-right: 10px;
        & > span:last-child {
          color: green;
          padding-left: 10px;
        }
      }
    }

    .owe-conntent {
      padding: 10px 20px;

      & > span {
        font-size: $fontSize-1;
      }
    }
  }
  }

.btn-text {
  font-size: $fontSize-3;
  color: #606266;
}

.w100 {
  width: 100%;
}
</style>